#include "gameboard.h"
#include "gamepiece.h"
#include "global.h"

Gameboard::Gameboard() {
  for (int x = 0; x < 8; x++) {
    for (int y = 2; y < 6; y++) {
      board[x][y] = 0;
    }
  }
  for (int i = 0; i < 8; i++) {
    board[i][1] = new Gamepiece(i, 1, PAWN, WHITE);
    board[i][6] = new Gamepiece(i, 6, PAWN, BLACK);
  }

  board[0][0] = new Gamepiece(0, 0, ROOK, WHITE);
  board[7][0] = new Gamepiece(7, 0, ROOK, WHITE);
  board[0][7] = new Gamepiece(0, 7, ROOK, BLACK);
  board[7][7] = new Gamepiece(7, 7, ROOK, BLACK);

  board[1][0] = new Gamepiece(1, 0, KNIGHT, WHITE);
  board[6][0] = new Gamepiece(6, 0, KNIGHT, WHITE);
  board[1][7] = new Gamepiece(1, 7, KNIGHT, BLACK);
  board[6][7] = new Gamepiece(6, 7, KNIGHT, BLACK);

  board[2][0] = new Gamepiece(2, 0, BISHOP, WHITE);
  board[5][0] = new Gamepiece(5, 0, BISHOP, WHITE);
  board[2][7] = new Gamepiece(2, 7, BISHOP, BLACK);
  board[5][7] = new Gamepiece(5, 7, BISHOP, BLACK);

  board[4][0] = new Gamepiece(3, 0, KING, WHITE);
  board[3][0] = new Gamepiece(4, 0, QUEEN, WHITE);
  board[4][7] = new Gamepiece(3, 7, KING, BLACK);
  board[3][7] = new Gamepiece(4, 7, QUEEN, BLACK);
}

Gameboard::~Gameboard() {
  for (int x = 0; x < 8; x++)
    for (int y = 0; y < 8; y++)
      if (board[x][y] != 0)
        delete board[x][y];
}

char *Gameboard::getFileName(int x, int y) {
  if (board[x][y] == 0)
    return 0;
  return board[x][y]->img;
}

void Gameboard::updatePosition(int oldx, int oldy, int newx, int newy) {
  if (board[newx][newy] != 0)
    delete board[newx][newy];
  board[newx][newy] = board[oldx][oldy];
  board[newx][newy]->initialPosition = false;
  board[oldx][oldy] = 0;
}

void Gameboard::removePiece(int x, int y) {
  delete board[x][y];
  board[x][y] = 0;
}

int Gameboard::getColor(int x, int y) const {
  if (board[x][y] == 0)
    return -1;  // error
   return board[x][y]->color;
}

int Gameboard::getType(int x, int y) const {
  if (board[x][y] == 0)
    return -1;  // error
  return board[x][y]->type;
}

bool Gameboard::atInitial(int x, int y) const {
  if (board[x][y] == 0)
    return 0;  // error
  return board[x][y]->initialPosition;
}
